from django.conf import settings
from django.template import RequestContext,loader
from django.shortcuts import render_to_response
from django import forms
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required,user_passes_test

from pacs.models import Task,TaskName,Problem,ProblemDescription
from forms_admin import AddFullTaskManipulator

from problem_admin import _add_problem

def _add_task(problem,slug,startTime,endTime,name):
	task = Task(problem=problem,slug=slug,startTime=startTime,endTime=endTime)
	task.save()

	taskName = TaskName(task=task,lang=settings.LANGUAGE_CODE[:2],name=name)
	taskName.save()

	return task

@user_passes_test(lambda u: u.has_perm("pacs.add_task") and u.has_perm("pacs.add_task_name") and u.has_perm("pacs.add_problem") and u.has_perm("pacs.add_problem_description"))
def add_full_task(request):

	c = RequestContext(request)
	manipulator = AddFullTaskManipulator()
	if request.POST:
		data = request.POST.copy()
		data.update(request.FILES)
		errors = manipulator.get_validation_errors(data)
		if not errors:
			#try:
				manipulator.do_html2python(data)
				problem = _add_problem(data['description'],data['input'],data['output'],data['testExamples'])
				task = _add_task(problem,data['slug'],data['startTime'],data['endTime'],data['name'])

			#else:
				return HttpResponseRedirect(reverse('pacs.views.show_task',None,(),{'task_slug':task.slug}))
	else:
		from datetime import datetime
		now = datetime.now()
		maxDate = datetime(2999,12,31)
		def cut_milis(s):
			return s[:s.find('.')]
		data = {'startTime':cut_milis(now.isoformat(' ')),'endTime':cut_milis(maxDate.isoformat(' '))}
		errors = {}
	c['form'] = forms.FormWrapper(manipulator,data,errors)
	return render_to_response('pacs/add_full_task.xhtml', c)
